package com.shangguosha.core;

import com.shangguosha.core.event.EventBus;
import com.shangguosha.core.event.GameStateEvent;
import com.shangguosha.core.lifecycle.Lifecycle;
import com.shangguosha.core.lifecycle.LifecycleState;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * 游戏对象基类
 * 所有游戏中的对象都应该继承此类
 */
@Data
@EqualsAndHashCode(of = "id")
public abstract class GameObject implements Lifecycle {
    protected String id;
    protected String name;
    protected boolean isActive;
    protected LifecycleState state = LifecycleState.CREATED;
    protected EventBus eventBus;
    
    public GameObject(String id, String name) {
        this.id = id;
        this.name = name;
        this.isActive = true;
        this.state = LifecycleState.CREATED;
    }
    
    /**
     * 设置事件总线
     */
    public void setEventBus(EventBus eventBus) {
        this.eventBus = eventBus;
    }
    
    /**
     * 发射事件
     */
    public void emit(String eventType, Object... data) {
        if (eventBus != null) {
            GameStateEvent event = new GameStateEvent(eventType, this);
            if (data.length > 0) {
                event.setData(data);
            }
            eventBus.publish(event);
        }
    }
    
    /**
     * 对象创建时的生命周期方法
     */
    @Override
    public void onCreate() {
        this.state = LifecycleState.CREATED;
        emit("object_created", this);
    }
    
    /**
     * 对象激活时的生命周期方法
     */
    @Override
    public void onActivate() {
        this.state = LifecycleState.ACTIVE;
        this.isActive = true;
        emit("object_activated", this);
    }
    
    /**
     * 对象更新时的生命周期方法
     */
    @Override
    public void onUpdate() {
        // 子类可以重写此方法
    }
    
    /**
     * 对象销毁时的生命周期方法
     */
    @Override
    public void onDestroy() {
        this.state = LifecycleState.DESTROYED;
        this.isActive = false;
        emit("object_destroyed", this);
    }
    
    /**
     * 获取当前生命周期状态
     */
    @Override
    public LifecycleState getState() {
        return state;
    }
    
    @Override
    public String toString() {
        return String.format("%s[id=%s, name=%s]", 
            this.getClass().getSimpleName(), id, name);
    }
}